<template>
  <!-- 派送计划列表 -->
  <div class="deliveHistory" style="margin-bottom: 20px;">
        <div :class="monthHis ? 'monthHisActive' : 'weekHis'" @click="monthHis = true">供货计划</div>
        <div :class="!monthHis ? 'weekHisActive':'weekHis'" @click="monthHis = false">计划列表</div>
    </div>
  <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form class="-mb-15px formBox" :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
            <el-form-item label="商砼企业：" prop="companyId">
                    <el-select v-model="queryParams.companyId" placeholder="请选择商砼企业" clearable class="!w-240px">
                        <el-option :label="item.nickname" :value="item.id" v-for="(item) in componyList" :key="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="配送日期" prop="endTime">
                    <el-date-picker
                    v-model="queryParams.endTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                    class="!w-240px"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
                    <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
                </el-form-item>
            <el-form-item>
                <div class="deliveHistory">
                    <div :class="monthHis ? 'monthHisActive' : 'weekHis'" @click="monthHis = true">月配送历史</div>
                    <div :class="!monthHis ? 'weekHisActive':'weekHis'" @click="monthHis = false">周配送历史</div>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button style="margin-left: 20px;" type="success" plain @click="handleExport" :loading="exportLoading"
               >
                <Icon icon="ep:download" class="mr-5px" /> 导出数据
                </el-button>
                <el-button type="primary"  @click="openForm('create')" plain>
                <Icon icon="ep:plus" class="mr-5px" /> 新增
                </el-button>
            </el-form-item>
        </el-form>
        <div style="padding-bottom: 15px;padding-top: 40px;">
            <el-table v-loading="loading" :data="list" @row-click="rowClick">
                <el-table-column type="selection" width="55" />
                <el-table-column label="总包" align="center" prop="companyName" />
                <el-table-column label="进度/总量" align="center">
                   <template  #default="row">
                    {{row.row.endNumber+'/'+row.row.needNumber}}
                   </template>
                </el-table-column>
                <el-table-column label="项目" align="center" prop="projectName" />
                <el-table-column label="地址" align="center" prop="address" />
                <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter"/>
                <!-- <el-table-column label="订单号" align="center" prop="startTime" /> -->
                <el-table-column label="配送时间" align="center"  prop="endTime" :formatter="dateFormatter"></el-table-column>
            </el-table>

        </div>
  </ContentWrap>
  <!-- 地图模式 -->
  <ContentWrap>
    <div class="deliveHistory" style="margin-bottom: 15px;">
        <div :class="dateFlag ? 'monthHisActive' : 'weekHis'" @click="dateFlag = true">日期分布</div>
        <div :class="!dateFlag ? 'weekHisActive':'weekHis'" @click="dateFlag = false">地图模式</div>
    </div>
    <div class="dateModeBig">
        <div class="dateMode" v-show="dateFlag">
            <div class="dateMode-top">
                <div class="dateMode-top-center">
                    <img class="date-left-arrow" src="../../../assets/imgs/leftArrow.png" alt="">
                    <div class="dateWord">2020年9月</div>
                    <img class="date-left-arrow" src="../../../assets/imgs/rightArrow.png" alt="">
                </div>

            </div>
            <div class="dateMode-bot-list">
                <div class="dateMode-bot-item" v-for="(item,index) in dateList" :key="index">
                    <div class="dateMode-bot-item-week">
                        <div class="dateMode-bot-week-day" v-if="weekChinesList[index]">{{weekChinesList[index]}}</div>
                        <div class="dateMode-bot-week-day productItem"  v-else-if="!weekChinesList[index] && (index == 8 || index == 9 || index == 10 || index == 24)">
                            <div class="productItemBox">
                                <div class="lineColor"></div>
                                <div class="productItemBox-right">
                                    <div class="address-product">双西小区1A</div>
                                    <div class="product-info">数量：20吨，产品：铝酸盐水泥</div>
                                </div>
                            </div>
                            <div class="productItemBox">
                                <div class="lineColor" style="background: rgba(63, 140, 255, 1);"></div>
                                <div class="productItemBox-right">
                                    <div class="address-product">保利.一号公馆</div>
                                    <div class="product-info">数量：20吨，产品：铝酸盐水泥</div>
                                </div>
                            </div>
                        </div>
                        <div class="dateMode-bot-week-day" style="background: unset" v-else>
                        </div>
                        <div class="dateMode-bot-item-num">{{index+1}}.</div>
                    </div>

                </div>
            </div>
        </div>
        <div id="map" class="map" v-show="!dateFlag"></div>
        <iframe id="geoPage" width=0 height=0 frameborder=0  style="display:none;" scrolling="no"
            src="https://apis.map.qq.com/tools/geolocation?key=XAXBZ-2BCK5-2B3IR-QV75W-2SDAV-7QFNX&referer=hhh">
        </iframe>
    </div>

  </ContentWrap>
  
  <!-- 表单弹窗：添加/修改 -->
  <PurchaseForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="deliveryPlan">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as UserApi from '@/api/system/user'
import * as PurchaseApi from '@/api/system/purchase'
import * as ProjectApi from '@/api/system/project'
import * as GoodsApi from '@/api/cms/goods'
import PurchaseForm from './PurchaseForm.vue'
const message = useMessage() // 消息弹窗
const router = useRouter() // 路由对象
const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    name: null,
    endTime:null,
    companyId: null,
})
const componyList = ref([])
const projectList = ref([])
const goodsList = ref([])
const weekChinesList = ref(['星期一','星期二','星期三','星期四','星期五'])
const dateList= ref([{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},])
const list = ref([])
const loading = ref(false)
const monthHis = ref(true)
const dateFlag = ref(false)
const exportLoading = ref(false)
const queryFormRef = ref() // 搜索的表单
onMounted(async() => {
    
    // 加载企业列表
  componyList.value = await UserApi.getSimpleCompanyList()
  let res  = await ProjectApi.getProjectPage({pageNo:1,pageSize:100})
  projectList.value = res.list
  const data = await GoodsApi.getGoodsPage({pageNo:1,pageSize:100})
  goodsList.value = data.list
  console.log(componyList.value,'data')
  getList()
  try{

    window.addEventListener('message', function(event) {
        // 接收位置信息 你的其他操作
        var loc = event.data;
        console.log('location', loc);
        if(loc && loc.lat && loc.lng){
        //    fixedPos(loc)
          nextTick(()=>{
            initmap(loc)
          })
        }

    }, false);
  }finally{
    nextTick(()=>{
      initmap()
    })
  }
})
/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log(queryParams,'queryParams')
    const data = await PurchaseApi.getPurchasePage(queryParams)
    console.log( list.value,' list.value------------------')

    list.value = data.list.map((item)=>{
      item.companyName = componyList.value.find(i=>i.id == item.companyId)?.nickname 
      item.projectName = projectList.value.find(i=>i.id == item.projectId)?.company 
      item.goodsName = goodsList.value.find(i=>i.id == item.goodsId)?.name 
      return {
        ...item
      }
    })
    // total.value = data.total
  } finally {
    loading.value = false
  }
}
const rowClick=(row)=>{
  console.log(row,'row')
    router.push({ path:'/deliveryPlan/detail',query:{id:row.id} })
}
const initmap=(loc)=>{
    
    var center = !loc ? new TMap.LatLng(24.45149381672781, 118.08619582145691) : new TMap.LatLng(loc.lat,loc.lng);
    //初始化地图
    var mapDom = document.getElementById("map");
    var map = new TMap.Map('map', {
        zoom:16,//设置地图缩放级别
        center: center,//设置地图中心点坐标
    });
    console.log(map,'111111')
    var path =  [
        new TMap.LatLng(24.45149381672781, 118.08619582145691),
        new TMap.LatLng(24.45372057921502,118.08825575798035),
        new TMap.LatLng( 24.458330243156805, 118.09078776329041),
    ]
    var polylineLayer = new TMap.MultiPolyline({
          map:map, // 绘制到目标地图
          // 折线样式定义
          styles: {
            style_blue: new TMap.PolylineStyle({
              color: '#ff8d00', // 线填充色
              width: 4, // 折线宽度
              borderWidth: 2, // 边线宽度
              borderColor: '#FFF', // 边线颜色
              lineCap: 'round', // 线端头方式
              eraseColor: 'rgb(172,172,172)',//擦除路径的颜色
            }),
          },
          geometries: [
            {
              id: 'erasePath',
              styleId: 'style_blue',
              paths: path,
            },
          ],
        });
        var marker = new TMap.MultiMarker({
          map:map, // 绘制到目标地图
          styles: {
            'car-down': new TMap.MarkerStyle({
              width: 40,
              height: 40,
              anchor: {
                x: 20,
                y: 20,
              },
              faceTo: 'map',
              rotate: 180,
              src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png',
            }),
            start: new TMap.MarkerStyle({
              width: 25,
              height: 35,
              anchor: {x: 16, y: 32},
              src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
            }),
            end: new TMap.MarkerStyle({
              width: 25,
              height: 35,
              anchor: {x: 16, y: 32},
              src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
            }),
          },
          geometries: [
            {
              id: 'car',
              styleId: 'car-down',
              position: path[0],
            },
            {
              id: 'start',
              styleId: 'start',
              position: path[1],
            },
            {
              id: 'end',
              styleId: 'end',
              position: path[2],
            },
          ],
        });
        startCar(marker,path,polylineLayer)
}
// 点击定位-定位到当前位置
const  fixedPos =(loc)=> {
//     console.log(loc,'定位成功')
//     var map = document.getElementById("map")
//     var pos = new qq.maps.LatLng(loc.lat,loc.lng)
    
//     var mapInfo = new qq.maps.Map(map, {
//         // 地图的中心地理坐标。
//         center: pos,
//         zoom:20
//     });
// // var marker = new qq.maps.Marker({
//     //     position: new qq.maps.LatLng(loc.lat,loc.lng), // 标记的经纬度
//     //     map, // 地图实例
//     // });
//      //创建一个Marker
//      var marker = new qq.maps.Marker({
//         //设置Marker的位置坐标
//         position: pos,
//         //设置显示Marker的地图
//         map: mapInfo
//     });
//     marker.setVisible(true);
//     //设置Marker的动画属性为从落下
//     marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
//     //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
//     marker.setDraggable(true);
//      //添加信息窗口
//      var info = new qq.maps.InfoWindow({
//         map: mapInfo
//     });
//     info.setPosition(marker.getPosition());
//     //标记Marker点击事件
//     qq.maps.event.addListener(marker, 'click', function() {
//         info.setPosition(marker.getPosition());
//     });
//     //设置Marker停止拖动事件
//     qq.maps.event.addListener(marker, 'dragend', function() {
//         // info.open();
//         console.log(marker.getPosition(),'11111155555')
//         info.setPosition(marker.getPosition());
//     });
  
//     if(qq.maps.Polyline){
//         var polyline = new qq.maps.Polyline({
//             path,
//             strokeColor: '#ff8d00',
//             strokeWeight: 10,
//             map:mapInfo
//         });
//         polyline.setMap(map);
//         startCar()
//     }

}
const startCar=(marker,path,polylineLayer) =>{
        // 使用marker 移动接口， https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocMarker
        //调用moveAlong动画 执行标记点动画开始
        marker.moveAlong(
          {
            car: {
              path: path,//移动路径的坐标串
              // duration:8000,//完成移动所需的时间，单位：毫秒
              speed: 250, //speed为指定速度，正整数，单位：千米/小时
            },
          },
          {
            autoRotation: true,//自动旋转
          }
        );
        //监听事件名
        marker.on('moving', (e) => {
          var passedLatLngs = e.car && e.car.passedLatLngs;
          if (passedLatLngs) {
            // 使用路线擦除接口 eraseTo, https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocVector
            polylineLayer.eraseTo(
              'erasePath',
              passedLatLngs.length - 1,
              passedLatLngs[passedLatLngs.length - 1]
            );
          }
        });
  
      }
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PurchaseApi.exportPurchase(queryParams)
    download.excel(data, '供货计划管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
</script>

<style scoped  lang="scss">
.formBox{
    display: flex;
    align-items: center;
    justify-content: space-between;   
}
.deliveHistory{
   
    width: 180px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    background: rgb(81, 123, 255);
    color: #fff;
    border-radius: 8px;
    border: 1px solid rgb(81, 123, 255);
}
.monthHisActive{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 27.5px;
    padding: 5px;
    text-align: center;
    background: #fff;
    color: #000;
    border-radius: 8px;
    border-top-right-radius: 21px;
    border-bottom-right-radius: 20px;
    width: 50%;
    cursor: pointer;
}
.weekHisActive{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 27.5px;
    padding: 5px;
    text-align: center;
    background: #fff;
    color: #000;
    border-radius: 8px;
    border-top-left-radius: 21px;
    border-bottom-left-radius: 20px;
    width: 50%;
    cursor: pointer;
}
.weekHis{
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 5px;
    text-align: center;
    color: #fff;
    border-radius: 8px;
    width: 45%;
    cursor: pointer
}
.dateModeBig{
    padding: 100px;
    background: rgba(249, 250, 255, 1);
    border-radius: 16px;
    padding-left: 272px;
}
.dateMode{
    background: #fff;
    border-radius: 24px;
    width: 1150px;
    height: 715px;
}
.dateMode-top{
    display: flex;
    justify-content: center;
    padding: 15px;
}
.dateMode-top-center{
    display: flex;
    align-items: center;
}
.date-left-arrow{
    cursor: pointer;
}
.dateMode-bot-list{
   width: 100%;
   height: calc(715px - 72px);
   display: flex;
    flex-wrap: wrap;
}
.dateMode-bot-item{
    width: 20%;
    height: 128px;
    border: 1px solid rgba(230, 235, 245, 1);
    padding: 12px;
}
.dateWord{
    padding: 0 50px;
}
.productItem{
    width: 195px !important;
    background: unset !important;
    height: 104px !important;
    flex-direction: column;
}
.dateMode-bot-item-week{
    display: flex;
    justify-content: space-between;
}
.dateMode-bot-week-day{
    font-size: 14px;
    color: rgba(125, 133, 146, 1);
    background: rgba(244, 249, 253, 1);
    width: 62px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 7px;
}
.dateMode-bot-item-num{
    font-size: 14px;
}
.productItemBox{
    display: flex;
    justify-content: space-between;
    height: 56px;
    background: rgba(244, 249, 253, 1);
    border-radius: 6px;
    align-items: center;
    margin-bottom: 10px;
}
.lineColor{
    width: 4px;
    height: 40px;
    background: rgba(222, 146, 235, 1);
    margin-right: 10px;
}
.productItemBox-right{
    
}
.address-product{
    font-size: 14px;
    color: #000;
    font-weight: bold;
}
.product-info{
    font-size: 12px;
}
#map {
    width: 100%;
    height: 1000px;
    border-radius: 20px;
    overflow: hidden
}
</style>